<template>
  <view class="dd-container">
    <!-- 顶部导航栏（日期+搜索框+日期选择） -->
    <view class="dd-header">
      <text class="header-date-full">{{ currentDateFull }}</text>
      <!-- 新增：完整日期显示 -->
      <view class="header-right">
        <uni-search-bar
          v-model="searchValue"
          placeholder="搜索考勤记录"
          :clearButton="none"
          :cancelButton="none"
          :bgColor="'#F8F8F8'"
          radius="20"
          @confirm="handleSearch">
          <view slot="searchIcon">
            <image
              src="/static/dd-icon-search.png"
              mode="aspectFit"
              class="search-icon"></image>
          </view>
        </uni-search-bar>
        <uni-datetime-picker
          type="date"
          :value="currentDate"
          @change="handleDateChange"
          class="date-picker"></uni-datetime-picker>
      </view>
    </view>

    <!-- 主要内容区 -->
    <scroll-view class="content" scroll-y>
      <!-- 打卡状态卡片 -->
      <view class="check-card">
        <!-- 今日状态 -->
        <view class="today-status">
          <text class="status-text">{{ statusText }}</text>
          <text class="status-time" v-if="checkInTime">
            今日{{ getCheckTypeText }}打卡时间：{{ formatTime(checkInTime) }}
          </text>
        </view>

        <!-- 地图区域（宽度铺满） -->
        <view class="map-wrapper">
          <map
            class="dd-map"
            provider="qqmap"
            :latitude="centerLatitude"
            :longitude="centerLongitude"
            :markers="markers"
            :scale="12"
            show-location></map>
          <view class="map-label">
            <text class="label-text">
              {{ currentAddress || "获取位置中..." }}
            </text>
          </view>
        </view>

        <!-- 打卡点信息 -->
        <view class="check-point-info">
          <text class="point-name">打卡点：{{ checkInPoint.name }}</text>
          <text class="distance">
            距离 {{ distance ? distance.toFixed(1) + "米" : "计算中" }}
            <text class="range">
              ({{ checkInRange }}米内正常打卡，外为外勤)
            </text>
          </text>
        </view>

        <!-- 打卡按钮（区分正常/外勤 上下班） -->
        <view class="check-btn-group">
          <button
            class="check-btn"
            :class="{
              disabled: hasCheckedInToday,
              normal: !isOutside && checkType === 'clockIn',
              outside: isOutside && checkType === 'clockIn',
            }"
            :disabled="hasCheckedInToday"
            @click="handleCheckIn('clockIn')"
            ref="checkBtn">
            {{ isOutside ? "外勤上班打卡" : "上班打卡" }}
          </button>
          <button
            class="check-btn"
            :class="{
              disabled: hasCheckedOutToday,
              normal: !isOutside && checkType === 'clockOut',
              outside: isOutside && checkType === 'clockOut',
            }"
            :disabled="hasCheckedOutToday"
            @click="handleCheckIn('clockOut')"
            ref="checkBtn">
            {{ isOutside ? "外勤下班打卡" : "下班打卡" }}
          </button>
        </view>
      </view>

      <!-- 快捷操作区 -->
      <view class="quick-actions">
        <view class="action-item" @click="showHistory">
          <image src="/static/dd-icon-clock.png" mode="aspectFit"></image>
          <text class="action-text">打卡记录</text>
        </view>
        <view class="action-item" @click="showRules">
          <image src="/static/dd-icon-file.png" mode="aspectFit"></image>
          <text class="action-text">考勤规则</text>
        </view>
        <view class="action-item" @click="showHelp">
          <image src="/static/dd-icon-help.png" mode="aspectFit"></image>
          <text class="action-text">帮助中心</text>
        </view>
      </view>

      <!-- 打卡记录列表 -->
      <view class="record-section">
        <text class="section-title">最近打卡记录</text>
        <view class="record-list">
          <view
            class="record-item"
            v-for="(item, index) in recentRecords"
            :key="index">
            <text class="record-date">{{ item.date }}</text>
            <text
              class="record-type"
              :class="item.isOutside ? 'outside' : 'normal'">
              {{ getRecordTypeText(item) }}
            </text>
            <text class="record-time">{{ formatTime(item.time) }}</text>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      searchValue: "",
      currentDate: new Date().toISOString().split("T")[0], // 日期（如2025-10-22）
      currentDateFull: "", // 完整日期（如2025-10-22 周三）
      checkInPoint: {
        name: "西安总部办公室",
        latitude: 34.19097,
        longitude: 108.881817,
      },
      checkInRange: 500,
      centerLatitude: 34.19097,
      centerLongitude: 108.881817,
      currentLocation: null,
      currentAddress: "",
      markers: [],
      distance: null,
      checkType: "clockIn", // clockIn=上班, clockOut=下班
      hasCheckedInToday: false,
      hasCheckedOutToday: false,
      checkInTime: "",
      statusText: "今日未打卡",
      recentRecords: [],
      isOutside: false, // 是否为外勤打卡
    };
  },

  onLoad() {
    this.initDate(); // 初始化完整日期
    this.initMarkers();
    this.checkTodayStatus();
    this.getLocation();
  },

  computed: {
    // 格式化打卡类型文本
    getCheckTypeText() {
      return this.isOutside
        ? this.checkType === "clockIn"
          ? "外勤上班"
          : "外勤下班"
        : this.checkType === "clockIn"
        ? "上班"
        : "下班";
    },
  },

  methods: {
    // 初始化完整日期（含星期）
    initDate() {
      const date = new Date();
      const week = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
      this.currentDateFull = `${date.getFullYear()}-${(date.getMonth() + 1)
        .toString()
        .padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")} ${
        week[date.getDay()]
      }`;
    },

    // 日期选择回调：切换日期后更新完整日期和打卡记录
    handleDateChange(e) {
      this.currentDate = e.value;
      this.initDate(); // 重新计算完整日期
      this.checkTodayStatus(); // 加载对应日期的打卡状态
    },

    // 搜索考勤记录
    handleSearch() {
      uni.showToast({
        title: `搜索：${this.searchValue}`,
        icon: "none",
      });
    },

    // 获取位置
    getLocation() {
      uni.getLocation({
        type: "gcj02",
        timeout: 15000,
        success: (res) => {
          this.currentLocation = res;
          this.centerLatitude = res.latitude;
          this.centerLongitude = res.longitude;
          this.addCurrentMarker();
          this.calculateDistance();
          this.getAddress(res.latitude, res.longitude);
        },
        fail: (err) => {
          this.currentAddress = "定位失败，请检查权限";
          console.error("定位失败：", err);
        },
      });
    },

    // 添加当前位置标记
    addCurrentMarker() {
      this.markers.push({
        id: 2,
        latitude: this.currentLocation.latitude,
        longitude: this.currentLocation.longitude,
        iconPath: "/static/dd-icon-current.png",
        width: 36,
        height: 36,
        anchor: { x: 0.5, y: 1 },
      });
    },

    // 计算距离并判断是否外勤
    calculateDistance() {
      const R = 6371000;
      const lat1 = this.currentLocation.latitude;
      const lon1 = this.currentLocation.longitude;
      const lat2 = this.checkInPoint.latitude;
      const lon2 = this.checkInPoint.longitude;

      const radLat1 = (lat1 * Math.PI) / 180;
      const radLat2 = (lat2 * Math.PI) / 180;
      const deltaLat = ((lat2 - lat1) * Math.PI) / 180;
      const deltaLon = ((lon2 - lon1) * Math.PI) / 180;

      const a =
        Math.sin(deltaLat / 2) ** 2 +
        Math.cos(radLat1) * Math.cos(radLat2) * Math.sin(deltaLon / 2) ** 2;
      this.distance = R * (2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)));
      this.isOutside = this.distance > this.checkInRange; // 超过范围则为外勤
    },

    // 获取地址（示例地址，可替换为腾讯地图API）
    getAddress(lat, lng) {
      this.currentAddress = "广东省广州市越秀区北京街道广州市人民政府";
    },

    // 格式化时间为“分:秒”格式
    formatTime(timeStr) {
      const [hour, minute, second] = timeStr.split(":");
      return `${parseInt(minute)}:${second}`;
    },

    // 处理打卡（区分正常/外勤 上下班）
    handleCheckIn(type) {
      const now = new Date();
      this.checkInTime = now.toLocaleTimeString("zh-CN", {
        hour12: false,
        minute: "2-digit",
        second: "2-digit",
      });
      this.checkType = type;

      const dateStr = this.currentDate;
      const newRecord = {
        date: dateStr,
        time: this.checkInTime,
        type: type,
        distance: this.distance ? this.distance.toFixed(1) : "未知",
        address: this.currentAddress,
        isOutside: this.isOutside, // 标记是否为外勤
      };

      this.recentRecords.unshift(newRecord);
      uni.setStorageSync("ddCheckInRecords", this.recentRecords);

      if (type === "clockIn") {
        this.hasCheckedInToday = true;
        this.statusText = `今日已${this.isOutside ? "外勤上班" : "上班"}打卡`;
      } else {
        this.hasCheckedOutToday = true;
        this.statusText = `今日已${this.isOutside ? "外勤下班" : "下班"}打卡`;
      }

      // 按钮按压动画
      const animation = uni.createAnimation({
        duration: 100,
        timingFunction: "ease-out",
      });

      animation.scale(0.98).step();
      this.animationData = animation.export();

      setTimeout(() => {
        animation.scale(1).step();
        this.animationData = animation.export();
      }, 100);

      uni.showToast({
        title: `${this.isOutside ? "外勤" : ""}${
          type === "clockIn" ? "上班" : "下班"
        }打卡成功`,
        icon: "success",
        duration: 1500,
      });
    },

    // 检查今日打卡状态（含历史日期查询）
    checkTodayStatus() {
      const records = uni.getStorageSync("ddCheckInRecords") || [];
      const todayRecords = records.filter(
        (item) => item.date === this.currentDate
      );

      this.hasCheckedInToday = todayRecords.some(
        (item) => item.type === "clockIn"
      );
      this.hasCheckedOutToday = todayRecords.some(
        (item) => item.type === "clockOut"
      );

      if (this.hasCheckedInToday && this.hasCheckedOutToday) {
        const hasOutside = todayRecords.some((item) => item.isOutside);
        this.statusText = hasOutside
          ? "今日已完成外勤上下班打卡"
          : "今日已完成上下班打卡";
      } else if (this.hasCheckedInToday) {
        const isIn = todayRecords.find((item) => item.type === "clockIn");
        this.statusText = isIn.isOutside
          ? "今日已外勤上班打卡，未下班打卡"
          : "今日已上班打卡，未下班打卡";
      } else if (this.hasCheckedOutToday) {
        const isOut = todayRecords.find((item) => item.type === "clockOut");
        this.statusText = isOut.isOutside
          ? "今日未上班打卡，已外勤下班打卡"
          : "今日未上班打卡，已下班打卡";
      } else {
        this.statusText = "今日未打卡";
      }

      // 加载最近3条记录（含历史日期）
      this.recentRecords = todayRecords
        .concat(records.filter((item) => item.date !== this.currentDate))
        .slice(0, 3);
    },

    // 打卡记录入口
    showHistory() {
      uni.navigateTo({ url: "/pages/history/history" });
    },

    // 考勤规则入口
    showRules() {
      uni.showToast({ title: "考勤规则功能开发中", icon: "none" });
    },

    // 帮助中心入口
    showHelp() {
      uni.showToast({ title: "帮助中心功能开发中", icon: "none" });
    },

    // 格式化记录类型文本
    getRecordTypeText(item) {
      return item.type === "clockIn"
        ? item.isOutside
          ? "外勤上班"
          : "上班"
        : item.isOutside
        ? "外勤下班"
        : "下班";
    },
  },
};
</script>

<style scoped>
/* 全局样式 */
.dd-container {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f7fa;
}

/* 顶部导航栏 */
.dd-header {
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1px solid #e5e5e5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-date-full {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.date-picker {
  width: 200rpx;
}

/* 搜索栏样式 */
.search-icon {
  width: 32rpx;
  height: 32rpx;
}

/* 打卡卡片 */
.check-card {
  margin: 20rpx;
  padding: 20rpx;
  background-color: #fff;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

/* 地图容器（宽度铺满） */
.map-wrapper {
  width: 100%;
  position: relative;
  height: 500rpx;
  border-radius: 8rpx;
  overflow: hidden;
}

.dd-map {
  width: 100%;
  height: 100%;
}

/* 地图标签 */
.map-label {
  position: absolute;
  bottom: 10rpx;
  left: 0;
  right: 0;
  padding: 8rpx 15rpx;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  font-size: 26rpx;
  text-align: center;
  margin: 0 10rpx;
  border-radius: 6rpx;
}

/* 打卡按钮组 */
.check-btn-group {
  display: flex;
  gap: 20rpx;
  margin-top: 20rpx;
}

.check-btn {
  flex: 1;
  height: 90rpx;
  line-height: 90rpx;
  font-size: 32rpx;
  border-radius: 24rpx;
  transition: all 0.15s ease;
}

.check-btn.normal {
  background: linear-gradient(135deg, #005eff 0%, #007bff 100%);
  box-shadow: 0 4rpx 12rpx rgba(0, 94, 255, 0.2);
  color: #fff;
}

.check-btn.outside {
  background: linear-gradient(135deg, #ff7d00 0%, #ffa43d 100%);
  box-shadow: 0 4rpx 12rpx rgba(255, 125, 0, 0.2);
  color: #fff;
}

.check-btn.disabled {
  background-color: #e5e5e5;
  box-shadow: none;
  color: #999;
}

.check-btn:active {
  transform: scale(0.98);
}

/* 快捷操作区 */
.quick-actions {
  display: flex;
  justify-content: space-around;
  margin: 20rpx;
  padding: 25rpx 0;
  background-color: #fff;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.action-item image {
  width: 40rpx;
  height: 40rpx;
}

.action-text {
  font-size: 24rpx;
  color: #666;
  margin-top: 10rpx;
}

/* 记录区域 */
.record-section {
  margin: 20rpx;
  background-color: #fff;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.section-title {
  display: block;
  padding: 20rpx 25rpx;
  font-size: 28rpx;
  color: #333;
  border-bottom: 1px solid #f5f5f5;
}

.record-list {
  padding: 10rpx 0;
}

.record-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 18rpx 25rpx;
  border-bottom: 1px solid #f5f5f5;
}

.record-item:last-child {
  border-bottom: none;
}

.record-date {
  font-size: 26rpx;
  color: #333;
}

.record-type {
  padding: 3rpx 12rpx;
  border-radius: 15rpx;
  font-size: 22rpx;
}

.record-type.normal {
  background-color: #e6f7ee;
  color: #00b42a;
}

.record-type.outside {
  background-color: #fff8e6;
  color: #ff7d00;
}

.record-time {
  font-size: 26rpx;
  color: #666;
}
</style>
